package com.mingqijia.gassafety.shared.utils.message;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.gap.basic.exception.BizException;
import com.google.common.base.Joiner;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.UrlConst;
import com.mingqijia.gassafety.shared.dto.*;
import com.mingqijia.gassafety.shared.utils.HttpUtil;
import com.mingqijia.gassafety.shared.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName SendMessageService.java
 * @createTime 2022年03月03日
 */
@Component
@Slf4j
public class SendMessageService {

    @Value(value = "${gassafety.warnStrategy.url}")
    public String goUrl;
    @Value(value = "${gassafety.warnStrategy.openUrl}")
    public String openGoUrl;
    @Value(value = "${gassafety.business.api.url}")
    public String webserver;
    @Value(value = "${gassafety.warnStrategy.openAppId}")
    public String openId;
    @Value(value = "${gassafety.warnStrategy.openAppSecret}")
    public String openSecret;
    @Value(value = "${gassafety.warnStrategy.privateFlag}")
    public boolean privateStatus = false;
    @Value(value = "${gassafety.zjwifi.orgCode}")
    public String zjOrgCode;

    /**
     * 短信、微信推送
     *
     * @param jsonData
     * @param spId
     * @return
     */
    public Map<String, Object> sendSms(Map<String, Object> jsonData, String spId) {

        if (privateStatus) goUrl = openGoUrl;
        log.info("ndMessageServSeiceImpl——sendSms,主要发送数据：{},type：{}",
                JSONObject.toJSONString(jsonData));
        String url = goUrl + UrlConst.SMS_SEND_WARNING.getUrl();
        Map<String, Object> resultMap = new HashMap<>();
        boolean result = true;
        resultMap.put("result", result);
        JSONObject jsonObject = null;
        String body = "";
        String errMsg = "";
        try {
            if (privateStatus) {
                String token = getToken();
                log.info("开放平台token：{}", token);
                if (StringUtils.isEmpty(token)) {
                    throw new BizException(token + "获取失败");
                }
                url = goUrl + UrlConst.SMS_SEND_WARNING_PRIVATE.getUrl();
                if (jsonData.containsKey("phones")) {
                    jsonData.put("phones", JSONObject.parse(jsonData.get("phones") + ""));
                }
                String jsonStr = openSign(jsonData, openSecret);
                jsonData.put("openSign", jsonStr);
                jsonData.put("data", JSONObject.parse(jsonData.get("data") + ""));
                if (jsonData.containsKey("openIds")) {
                    jsonData.put("openIds", JSONObject.parse(jsonData.get("openIds") + ""));
                }
                body = HttpUtil.getBody(JSONObject.toJSONString(jsonData), url, spId, token);
            } else {

                String jsonStr = JSONObject.toJSONString(jsonData);
                body = HttpUtil.getBody(jsonStr, url, spId);
            }

            log.info("SendMessageServiceImpl——url：{}", url);

            log.info("SendMessageServiceImpl——sendSms,响应结果body：{}",
                    JSONObject.toJSONString(body));
            if (StringUtils.isEmpty(body)) return resultMap;
            jsonObject = JSONObject.parseObject(body);
            if (jsonObject == null) return resultMap;
            if (Integer.parseInt(jsonObject.get("code") + "") != 0) {
                errMsg = null==jsonObject.get("msg")?"":jsonObject.getString("msg");
                result = false;
            }else if (null==jsonObject.get("data") || ObjectUtils.isEmpty(jsonData.get("data"))){
                //数据为空时，返回结果为失败
                result = false;
                errMsg = "消息发送后返回结果为空";
            }
            resultMap.put("data", jsonObject.get("data"));
        } catch (Exception e) {
            log.error("sendSms-error:{}", e);
            result = false;
        }
        resultMap.put("errMsg", errMsg);
        resultMap.put("result", result);

        return resultMap;
    }

    /**
     * 获取消息的模板内容
     *
     * @param taskDetailParam
     * @return
     */
    public TaskDetailRespDTO getMsgTemplateContent(TaskDetailParamDTO taskDetailParam) {
        TaskDetailRespDTO taskDetailRespDTO = new TaskDetailRespDTO();
        String templateContent = Constants.MSG_CODE_CONTENT_MAP.get(taskDetailParam.getCode());
        taskDetailRespDTO.setTemplateContent(templateContent);
        try {
            String spId = taskDetailParam.getSpId();
            Map<String, Object> jsonData = new HashMap<>();
            jsonData.put("orgCode", taskDetailParam.getOrgCode());
            jsonData.put("code", taskDetailParam.getCode());
            if (privateStatus) goUrl = openGoUrl;
            log.info("getMsgTemplateContent-主要发送数据：{},请求地址：{}", JSONObject.toJSONString(jsonData), goUrl);
            JSONObject jsonObject = null;
            String url = goUrl + UrlConst.SMS_TASK_CONTENT.getUrl();
            String body = "";
            if (privateStatus) {
                url = goUrl + UrlConst.SMS_TASK_CONTENT_PRIVATE.getUrl();
                String token = getToken();
                log.info("getMsgTemplateContent-开放平台token：{}", token);
                if (StringUtils.isEmpty(token)) {
                    throw new BizException(token + "获取失败");
                }
                jsonData.put("openTimestamp", System.currentTimeMillis() / 1000 + "");
                String jsonStr = openSign(jsonData, openSecret);
                jsonData.put("openSign", jsonStr);
                jsonData.put("data", JSONObject.parse(jsonData.get("data") + ""));
                body = HttpUtil.getBody(JSONObject.toJSONString(jsonData), url, spId, token);
            } else {
                String jsonStr = JSONObject.toJSONString(jsonData);
                body = HttpUtil.getBody(jsonStr, url, spId);
            }
            log.info("getMsgTemplateContent——url：{}", url);
            log.info("getMsgTemplateContent——taskDetail,响应结果body：{}", JSONObject.toJSONString(body));
            if (StringUtils.isEmpty(body))
                return taskDetailRespDTO;
            jsonObject = JSONObject.parseObject(body);
            if (jsonObject == null)
                return taskDetailRespDTO;
            if (Integer.parseInt(jsonObject.get("code") + "") != 0) {
                return taskDetailRespDTO;
            } else {
                JSONObject data = jsonObject.getJSONObject("data");
                if (CollectionUtil.isEmpty(data) || StringUtils.isEmpty(data.get("templateContent")))
                    return taskDetailRespDTO;
                taskDetailRespDTO.setTemplateContent(data.getString("templateContent"));
            }
        } catch (Exception e) {
            log.error("getMsgTemplateContent-error:{}", e);
        }
        log.info("getMsgTemplateContent-taskDetailRespDTO:{}", JSONObject.toJSONString(taskDetailRespDTO));
        return taskDetailRespDTO;
    }

    /**
     * 获取任务模板列表
     * @param paramDTO
     * @return
     */
    public List<TaskTemplateListRespDTO> getMsgTemplateList(TaskTemplateListParamDTO paramDTO) {
        try {
            String spId = paramDTO.getSpId();
            Map<String, Object> jsonData = new HashMap<>();
            jsonData.put("orgCode", paramDTO.getOrgCode());
            if (!StringUtils.isEmpty(paramDTO.getCode())) {
                jsonData.put("code", paramDTO.getCode());
            }
            String codePrefix = "";
            if (!StringUtils.isEmpty(paramDTO.getCodePrefix())) {
                codePrefix = "^" + paramDTO.getCodePrefix() + "(_)?(\\d*)$"; //正则匹配^Alarm_equipment_strategy(_)?\\d*$
                jsonData.put("codePrefix", codePrefix);
            }
            jsonData.put("msgType", paramDTO.getMsgType());
            if (privateStatus) goUrl = openGoUrl;
            log.info("getMsgTemplateList-主要发送数据：{},请求地址：{}", JSONObject.toJSONString(jsonData), goUrl);
            String url = goUrl + UrlConst.SMS_TASK_TEMPLATE_LIST.getUrl();
            String body = "";
            if (privateStatus) {
                url = goUrl + UrlConst.SMS_TASK_TEMPLATE_LIST_PRIVATE.getUrl();
                String token = getToken();
                log.info("getMsgTemplateList-开放平台token：{}", token);
                if (StringUtils.isEmpty(token)) {
                    throw new BizException(token + "获取失败");
                }
                jsonData.put("openTimestamp", System.currentTimeMillis() / 1000 + "");
                String jsonStr = openSign(jsonData, openSecret);
                jsonData.put("openSign", jsonStr);
                jsonData.put("data", JSONObject.parse(jsonData.get("data") + ""));
                body = HttpUtil.getBody(JSONObject.toJSONString(jsonData), url, spId, token);
            } else {
                String jsonStr = JSONObject.toJSONString(jsonData);
                body = HttpUtil.getBody(jsonStr, url, spId);
            }
            log.info("getMsgTemplateList——url：{}", url);
            log.info("getMsgTemplateList——taskDetail,响应结果body：{}", JSONObject.toJSONString(body));
            if (StringUtils.isEmpty(body))
                return Collections.emptyList();
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (jsonObject == null || !jsonObject.containsKey("code") || !jsonObject.containsKey("data")) {
                return Collections.emptyList();
            } else if (null == jsonObject.getInteger("code") || jsonObject.getInteger("code") != 0) {
                return Collections.emptyList();
            } else {
                JSONArray data = jsonObject.getJSONArray("data");
                if (CollectionUtil.isEmpty(data))
                    return Collections.emptyList();
                List<TaskTemplateListRespDTO> result = JSONObject.parseArray(JSONObject.toJSONString(data), TaskTemplateListRespDTO.class);
                if (!StringUtils.isEmpty(codePrefix)) {
                    Pattern pattern = Pattern.compile(codePrefix);
                    for (TaskTemplateListRespDTO item : result) {
                        String number = "0";
                        item.setIsDefault(0);
                        if (item.getCode().equals(paramDTO.getCodePrefix())) {
                            number = "-99";
                            item.setIsDefault(1);
                        }
                        try {
                            Matcher matcher = pattern.matcher(item.getCode());
                            if (matcher.matches() && !StringUtils.isEmpty(matcher.group(2))) {
                                number = matcher.group(2);
                            }
                        } catch (Exception e) {
                            log.error("getMsgTemplateList number error", e);
                        }
                        item.setOrder(Integer.parseInt(number));
                    }
                    result = result.stream().sorted(Comparator.comparing(TaskTemplateListRespDTO::getOrder))
                            .collect(Collectors.toList());
                }
                log.info("getMsgTemplateList-taskTemplateListRespDTO:{}", JSONObject.toJSONString(result));
                return result;
            }
        } catch (Exception e) {
            log.error("getMsgTemplateList-error", e);
        }
        return Collections.emptyList();
    }

    /**
     * 发送回执
     *
     * @param jsonData
     * @param spId
     * @return
     */
    public Map<String, Object> subTaskDetail(Map<String, Object> jsonData, String spId) {
        if (privateStatus) goUrl = openGoUrl;
        jsonData.put("openTimestamp", System.currentTimeMillis() / 1000 + "");
        log.info("subTaskDetail-主要发送数据：{}", JSONObject.toJSONString(jsonData));
        JSONObject jsonObject = null;
        Map<String, Object> resMap = null;
        String url = goUrl + UrlConst.SUB_SMS_TASK_DETAIL.getUrl();
        String body = "";
        try {
            if (privateStatus) {
                url = goUrl + UrlConst.SMS_SUB_TASK_DETAIL_PRIVATE.getUrl();
                String token = getToken();
                log.info("subTaskDetail-开放平台token：{}", token);
                if (StringUtils.isEmpty(token)) {
                    throw new BizException(token + "获取失败");
                }
                String jsonStr = openSign(jsonData, openSecret);
                jsonData.put("openSign", jsonStr);
                jsonData.put("data", JSONObject.parse(jsonData.get("data") + ""));
                body = HttpUtil.getBody(JSONObject.toJSONString(jsonData), url, spId, token);
            } else {
                String jsonStr = JSONObject.toJSONString(jsonData);
                body = HttpUtil.getBody(jsonStr, url, spId);
            }

            log.info("subTaskDetail——url：{}", url);
            log.info("subTaskDetail——sendSms,响应结果body：{}",
                    JSONObject.toJSONString(body));
            if (StringUtils.isEmpty(body)) return null;
            jsonObject = JSONObject.parseObject(body);
            if (jsonObject == null) return null;
            if (Integer.parseInt(jsonObject.get("code") + "") != 0) {
                return null;
            } else {
                JSONArray data = jsonObject.getJSONArray("data");
                if (CollectionUtil.isEmpty(data)) return null;
                resMap = new HashMap<>();
                for (Object datum : data) {
                    JSONObject json = JSONObject.parseObject(datum + "");
                    if ("发送失败".equals(json.get("sendStatus"))) {
                        resMap.put("errorMsg", json.get("remark"));
                    }
                }
            }
        } catch (Exception e) {
            log.error("subTaskDetail-error:{}", e);
            resMap.put("errorMsg",
                    e.getMessage().length() > 100 ? e.getMessage().substring(0, 100) : e.getMessage());
        }

        return resMap;

    }

    /**
     * 参数封装
     *
     * @param phone    手机号
     * @param code     短信模版
     * @param orgCode  组织编码  String orgCode = companyService.getOrgCode(spId);
     * @param param    短信模版参数
     * @param msgType  类型："wxtpl"、"sms"
     * @param openIds  微信推送参数
     * @param subsCode 非必填
     * @param phones   微信推送参数
     * @param from     0非紫荆 1紫荆
     * @return
     */
    public Map<String, Object> getRequestParam(String phone, String code, String orgCode
            , Map<String, Object> param, String msgType, List<String> openIds, String subsCode
            , List<String> phones, int from) {
        log.info("getRequestParam-param:{},{},{}", phone, orgCode, subsCode);
        if (Constants.ZJ_EQUIPMENT_FROM == from) orgCode = zjOrgCode;
        Map<String, Object> params = new HashMap<>();
        if (!StringUtils.isEmpty(phone)) params.put("phone", phone);
        if (!CollectionUtil.isEmpty(openIds)) params.put("openIds", openIds);
        if (!CollectionUtil.isEmpty(phones)) params.put("phones", phones);
        if (!StringUtils.isEmpty(subsCode)) params.put("subsCode", subsCode);
        if (!StringUtils.isEmpty(code)) params.put("code", code);
        if (!StringUtils.isEmpty(orgCode)) params.put("orgCode", orgCode);
        if (!StringUtils.isEmpty("msgType")) params.put("msgType", msgType);
        if (param != null) params.put("data", param);
        if (privateStatus) {
            if (!StringUtils.isEmpty(openIds)) params.put("openIds", JSONObject.toJSONString(openIds));
            params.put("openTimestamp", System.currentTimeMillis() / 1000 + "");
            if (param != null) params.put("data", JSONObject.toJSONString(param));
        }
        return params;
    }

    public static String openSign(Map<String, Object> map, String... keys) {
        log.info("sign map = [{}],keys = [{}]", map.toString(), keys);
        Map<String, Object> treeMap = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);
        // 排序
        treeMap.putAll(map);
        List<String> params = new ArrayList<>(treeMap.size());
        for (Map.Entry<String, Object> entry : treeMap.entrySet()) {
            if ("openSign".equals(entry.getKey())) {
                continue;
            }
            StringBuilder sb = new StringBuilder();
            sb.append(entry.getKey()).append("=");
            Object value = entry.getValue();
            if (value instanceof JSONObject) {
                sb.append(((JSONObject) value).toString(SerializerFeature.WriteMapNullValue));
            } else if (value instanceof JSONArray) {
                sb.append(((JSONArray) value).toString(SerializerFeature.WriteMapNullValue));
            } else {
                sb.append(String.valueOf(value));
            }
            params.add(sb.toString());
        }
        String signStr = Joiner.on("&").join(params);
        StringBuilder keySb = new StringBuilder();
        keySb.append(signStr);
        for (String key : keys) {
            keySb.append(key);
        }
        log.info("sb = [{}],MD5 SB=[{}]", keySb.toString(), MD5Util.encrypt(keySb.toString()).toUpperCase());
        return MD5Util.encryptUpper(keySb.toString());
    }

    public String getToken() {
        String token = "";
        Map<String, Object> params = new HashMap<>();
        params.put("openAppId", openId);
        params.put("openAppSecret", openSecret);
        try {
            String body = HttpUtil.getBody(JSONObject.toJSONString(params),
                    goUrl + UrlConst.OPEN_TOKEN.getUrl(), "", "");
            if (StringUtils.isEmpty(body)) return null;
            log.info("getToken-response:{}", body);
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (Integer.parseInt(jsonObject.getString("code")) == 0) {
                JSONObject data = jsonObject.getJSONObject("data");
                token = data.getString("token");
            }
        } catch (Exception e) {
            log.error("getToken-error:{}", e);
            return null;
        }
        return token;
    }


    //发送本地消息
    public Map<String, Object> sendLocalSms(JSONObject jsonData, String spId) {

        log.info("SendMessageServiceImpl——sendLocalSms,主要发送数据：{}",
                JSONObject.toJSONString(jsonData));
        String url = webserver + UrlConst.SMS_SEND_LOCAL_WARNING.getUrl();
        Map<String, Object> resultMap = new HashMap<>();
        boolean result = true;
        resultMap.put("result", result);
        JSONObject jsonObject = null;
        String body = "";
        try {
            body = HttpUtil.getBody(JSONObject.toJSONString(jsonData), url, spId);
            log.info("SendMessageServiceImpl——url：{}", url);
            log.info("SendMessageServiceImpl——sendLocalSms,响应结果body：{}",
                    JSONObject.toJSONString(body));
            if (StringUtils.isEmpty(body)) return resultMap;
            jsonObject = JSONObject.parseObject(body);
            if (jsonObject == null) return resultMap;
            if (Integer.parseInt(jsonObject.get("code") + "") != 0) {
                result = false;
            }
            resultMap.put("data", jsonObject.get("data"));
        } catch (Exception e) {
            log.error("sendLocalSms-error:{}", e);
            result = false;
        }
        resultMap.put("result", result);

        return resultMap;
    }

    /**
     * 参数封装
     *
     * @param code    短信模版
     * @param orgCode 组织编码  String orgCode = companyService.getOrgCode(spId);
     * @return
     */
    public Map<String, Object> getRequestParam(String orgCode, String code) {
        log.info("getRequestParam-param:{},{}", orgCode, code);
        Map<String, Object> params = new HashMap<>();
        if (!StringUtils.isEmpty(code)) params.put("code", code);
        if (!StringUtils.isEmpty(orgCode)) params.put("orgCode", orgCode);
        return params;
    }

    /**
     * 获取短信内容
     *
     * @param code
     * @param param
     * @param assembleTemplate
     * @return
     */
    public String getSmsContent(String code, Map<String, Object> param, AssembleTemplateDTO assembleTemplate) {
        TaskDetailParamDTO smsTaskDetailParam = new TaskDetailParamDTO();
        smsTaskDetailParam.setSpId(assembleTemplate.getSpId());
        smsTaskDetailParam.setOrgCode(assembleTemplate.getOrgCode());
        String tCode = code;
        if (!StringUtils.isEmpty(assembleTemplate.getSmsMsgCode()) &&
                !"null".equalsIgnoreCase(assembleTemplate.getSmsMsgCode()) &&
                !assembleTemplate.getSmsMsgCode().trim().isEmpty()){
            tCode = assembleTemplate.getSmsMsgCode();
        }
        log.info("getSmsContent code:{}, tCode:{}",code,tCode);
        smsTaskDetailParam.setCode(tCode);
        TaskDetailRespDTO smsTaskDetailResp = getMsgTemplateContent(smsTaskDetailParam);
        String smsContent = smsTaskDetailResp.getTemplateContent();
        String content = "";
        switch (code){
            case Constants.WARN_STRATEGY:
            case Constants.WARN_ALARM_STRATEGY:
                content = smsContent.replace("#Time#", param.getOrDefault("Time", "").toString())
                        .replace("#value#", param.getOrDefault("value", "").toString())
                        .replace("#EquipmentName#", param.getOrDefault("EquipmentName", "").toString())
                        .replace("#position#", param.getOrDefault("position", "").toString())
                        .replace("#Position#", param.getOrDefault("Position", "").toString())
                        .replace("#Equipmenttype#", param.getOrDefault("Equipmenttype", "").toString())
                        .replace("#IMEI#", param.getOrDefault("IMEI", "").toString())
                        .replace("#Equipment_status#", param.getOrDefault("Equipment_status", "").toString())
                        .replace("#phone#", param.getOrDefault("phone", "").toString())
                        .replace("#UserID#", param.getOrDefault("UserID", "").toString())
                        .replace("#Name#", param.getOrDefault("Name", "").toString())
                        .replace("#address#", param.getOrDefault("address", "").toString())
                        .replace("#EquipmentName#", param.getOrDefault("EquipmentName", "").toString())
                        .replace("#subsName#", param.getOrDefault("subsName", "").toString())
                        .replace("#factoryName#", param.getOrDefault("factoryName", "").toString())
                        .replace("#CustomerName#", param.getOrDefault("CustomerName", "").toString());
                break;
            case Constants.RUNNING_STRATEGY_FAULT:
            case Constants.RUNNING_STRATEGY_OFFLINE:
            case Constants.RUNNING_STRATEGY_SERVICE:
                content = smsContent.replace("#Time#", param.getOrDefault("Time", "").toString())
                        .replace("#position#", param.getOrDefault("position", "").toString())
                        .replace("#verb#", param.getOrDefault("verb", "").toString())
                        .replace("#Position#", param.getOrDefault("position", "").toString())
                        .replace("#IMEI#", param.getOrDefault("IMEI", "").toString())
                        .replace("#phone#", param.getOrDefault("phone", "").toString())
                        .replace("#address#", param.getOrDefault("address", "").toString())
                        .replace("#subsName#", param.getOrDefault("subsName", "").toString())
                        .replace("#factoryName#", param.getOrDefault("factoryName", "").toString())
                        .replace("#Name#", param.getOrDefault("Name", "").toString())
                        .replace("#Equipmenttype#", param.getOrDefault("Equipmenttype", "").toString())
                        .replace("#CustomerName#", param.getOrDefault("CustomerName", "").toString());
                break;
            case Constants.FAULT_ALARM_STRATEGY:
            case Constants.REST_ALARM_STRATEGY:
            case Constants.SERVICE_ALARM_STRATEGY:
                content = smsContent.replace("#Time#", param.getOrDefault("Time", "").toString())
                        .replace("#verb#", param.get("verb") + "")
                        .replace("#Name#", param.get("Name") + "")
                        .replace("#Position#", param.get("Position") + "")
                        .replace("#Equipmenttype#", param.get("Equipmenttype") + "")
                        .replace("#subsName#", param.get("subsName") + "")
                        .replace("#address#", param.get("address") + "")
                        .replace("#IMEI#", param.getOrDefault("IMEI", "").toString())
                        .replace("#phone#", param.getOrDefault("phone", "").toString())
                        .replace("#factoryName#", param.getOrDefault("factoryName", "").toString())
                        .replace("#CustomerName#", param.getOrDefault("CustomerName", "").toString());
                break;
            case Constants.RUNNING_STRATEGY_REPORT:
            case Constants.RUNNING_ALARM_STRATEGY:
                content = smsContent.replace("#Date#", param.getOrDefault("Date", "").toString())
                    .replace("#phone#", param.getOrDefault("phone", "").toString())
                    .replace("#address#", param.getOrDefault("address", "").toString())
                    .replace("#subsName#", param.getOrDefault("subsName", "").toString())
                    .replace("#Name#", param.getOrDefault("Name", "").toString())
                    .replace("#position#", param.getOrDefault("position", "").toString())
                    .replace("#Position#", param.getOrDefault("position", "").toString())
                    .replace("#Equipmenttype#", param.getOrDefault("Equipmenttype", "").toString())
                    .replace("#CustomerName#", param.getOrDefault("CustomerName", "").toString());
                break;
            default:
                content = smsContent.replace("#Time#", param.getOrDefault("Time", "").toString())
                        .replace("#value#", param.getOrDefault("value", "").toString())
                        .replace("#EquipmentName#", param.getOrDefault("EquipmentName", "").toString())
                        .replace("#position#", param.getOrDefault("position", "").toString())
                        .replace("#Position#", param.getOrDefault("position", "").toString())
                        .replace("#Equipmenttype#", param.getOrDefault("Equipmenttype", "").toString())
                        .replace("#IMEI#", param.getOrDefault("IMEI", "").toString())
                        .replace("#Equipment_status#", param.getOrDefault("Equipment_status", "").toString())
                        .replace("#phone#", param.getOrDefault("phone", "").toString())
                        .replace("#UserID#", param.getOrDefault("UserID", "").toString())
                        .replace("#Name#", param.getOrDefault("Name", "").toString())
                        .replace("#address#", param.getOrDefault("address", "").toString())
                        .replace("#EquipmentName#", param.getOrDefault("EquipmentName", "").toString())
                        .replace("#subsName#", param.getOrDefault("subsName", "").toString())
                        .replace("#factoryName#", param.getOrDefault("factoryName", "").toString())
                        .replace("#CustomerName#", param.getOrDefault("CustomerName", "").toString());
                break;
        }
        return content;
    }

    /**
     * 获取微信内容
     *
     * @param code
     * @param param
     * @param assembleTemplate
     * @return
     */
    public String getWxContent(String code, Map<String, Object> param, AssembleTemplateDTO assembleTemplate) {
        TaskDetailParamDTO wxTaskDetailParam = new TaskDetailParamDTO();
        wxTaskDetailParam.setSpId(assembleTemplate.getSpId());
        wxTaskDetailParam.setOrgCode(assembleTemplate.getOrgCode());
        String tCode = code;
        if (!StringUtils.isEmpty(assembleTemplate.getWxMsgCode()) &&
                !"null".equalsIgnoreCase(assembleTemplate.getWxMsgCode()) &&
                !assembleTemplate.getWxMsgCode().trim().isEmpty()) {
            tCode = assembleTemplate.getWxMsgCode();
        }
        log.info("getWxContent code:{}, tCode:{}", code, tCode);
        wxTaskDetailParam.setCode(tCode);
        TaskDetailRespDTO wxTaskDetailResp = getMsgTemplateContent(wxTaskDetailParam);
        String wxContent = wxTaskDetailResp.getTemplateContent();
        String content = "";
        switch (code){
            case Constants.RUNNING__WX_STRATEGY_FAULT:
            case Constants.RUNNING__WX_STRATEGY_OFFLINE:
                content = wxContent.replace("$[Time]", param.getOrDefault("Time", "").toString())
                        .replace("$[IMEI]", param.getOrDefault("IMEI", "").toString())
                        .replace("$[position]", param.getOrDefault("position", "").toString())
                        .replace("$[phone]", param.getOrDefault("phone", "").toString())
                        .replace("$[EquipmentName]", param.getOrDefault("EquipmentName", "").toString())
                        .replace("$[Name]", param.getOrDefault("Name", "").toString())
                        .replace("$[UserID]", param.getOrDefault("UserID", "").toString())
                        .replace("$[address]", param.getOrDefault("address", "").toString())
                        .replace("$[subsName]", param.getOrDefault("subsName", "").toString())
                        .replace("$[subsCode]", param.getOrDefault("subsCode", "").toString())
                        .replace("$[factoryName]", param.getOrDefault("factoryName", "").toString())
                        .replace("$[Equipmenttype]", param.getOrDefault("Equipmenttype", "").toString())
                        .replace("$[CustomerName]", param.getOrDefault("CustomerName", "").toString());
                break;
            case Constants.RUNNING__WX_STRATEGY_REPORT:
                content = wxContent.replace("$[Date]", param.getOrDefault("Date", "").toString())
                    .replace("$[address]", param.getOrDefault("address", "").toString())
                    .replace("$[subsName]", param.getOrDefault("subsName", "").toString())
                    .replace("$[subsCode]", param.getOrDefault("subsCode", "").toString())
                    .replace("$[CustomerName]", param.getOrDefault("CustomerName", "").toString());
                break;
            case Constants.RUNNING__WX_STRATEGY_SERVICE:
                content = wxContent.replace("#verb#", param.getOrDefault("verb", "").toString())
                        .replace("$[Time]", param.getOrDefault("Time", "").toString())
                        .replace("$[IMEI]", param.getOrDefault("IMEI", "").toString())
                        .replace("$[address]", param.getOrDefault("address", "").toString())
                        .replace("$[subsName]", param.getOrDefault("subsName", "").toString())
                        .replace("$[subsCode]", param.getOrDefault("subsCode", "").toString())
                        .replace("$[factoryName]", param.getOrDefault("factoryName", "").toString())
                        .replace("$[CustomerName]", param.getOrDefault("CustomerName", "").toString());
                break;
            case Constants.WARN__WX_STRATEGY:
            default:
                content = wxContent.replace("$[Time]", param.getOrDefault("Time", "").toString())
                        .replace("$[value]", param.getOrDefault("value", "").toString())
                        .replace("$[position]", param.getOrDefault("position", "").toString())
                        .replace("$[Equipmenttype]", param.getOrDefault("Equipmenttype", "").toString())
                        .replace("$[IMEI]", param.getOrDefault("IMEI", "").toString())
                        .replace("$[Equipment_status]", param.getOrDefault("Equipment_status", "").toString())
                        .replace("$[phone]", param.getOrDefault("phone", "").toString())
                        .replace("$[EquipmentName]", param.getOrDefault("EquipmentName", "").toString())
                        .replace("$[Name]", param.getOrDefault("Name", "").toString())
                        .replace("$[UserID]", param.getOrDefault("UserID", "").toString())
                        .replace("$[address]", param.getOrDefault("address", "").toString())
                        .replace("$[subsName]", param.getOrDefault("subsName", "").toString())
                        .replace("$[subsCode]", param.getOrDefault("subsCode", "").toString())
                        .replace("$[factoryName]",param.getOrDefault("factoryName", "").toString())
                        .replace("$[CustomerName]", param.getOrDefault("CustomerName", "").toString());
                break;
        }
        return content;
    }

}


